import { request } from "../../request/index.js";
import { requestPayment,showToast } from '../../utils/asyncWx';
Page({
  data: {
    address: {},
    cartList: [],
    totalCost: 0,
    totalNum: 0
  },
  onShow: function () {
    const address = wx.getStorageSync("address");
    let cartList = wx.getStorageSync("cart") || [];
    cartList = cartList.filter(v => v.checked)
    //计算全选
    let totalCost = 0
    let totalNum = 0
    cartList.forEach((r) => {
      totalCost += r.goods_price * r.num
      totalNum += r.num
    })
    this.setData({
      address,
      cartList,
      totalCost,
      totalNum
    })
  },
  async handleOrderPay(){
    try {
      const token = wx.getStorageSync('token')
      if (!token) {
        wx.navigateTo({
          url:'/pages/auth/index',
          success:(res)=>{
          }
        })
        return
      }
      //请求头
      const header ={Authorization: token}
      //请求体
      const order_price = this.data.totalCost
      const consignee_addr = this.data.address.all
      let goods=[]
      const cart = this.data.cartList
      //goods
      cart.forEach(v=>goods.push({
        goods_id:v.goods_id,
        goods_number:v.num,
        goods_price:v.goods_price
      }))
      const orderParams={order_price,consignee_addr,goods}
      //发送请求
      const {order_number} = await request({url:"/my/orders/create",methods:"POST",data:orderParams,header})
      //let order_number = res === null ? 8967 : res
      /* let order_number
      if (res==null) {
        let order_number=67522
      } */
      //预支付
      const {pay} = await request({url:"/my/orders/req_unifiedorder",methods:"POST",data:{order_number},header})
      //发起微信支付
      await requestPayment(pay)
      //查看后台状态
      const res = await request({url:"/my/orders/chkOrder",methods:"POST",data:{order_number},header})
      await showToast({title:res})
      //删除缓存
      let newCart = wx.getStorageSync('cart')
      newcart=newCart.filter(v=>!v.checked) 
      wx.setStorageSync("cart", newCart);
        
      //成功后跳转
      wx.navigateTo({
        url: '/pages/order/index',
      });
        
    } catch (error) {
      await showToast({title:"支付失败"})
      console.log(error);
    }

  }
})